package com.sym.architecture.vm

import androidx.lifecycle.ViewModel
import com.sym.architecture.network.Api
import com.sym.architecture.network.ApiInterface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import java.lang.IllegalArgumentException


suspend fun <T> ViewModel.flowRequest(request: suspend ApiInterface.() -> T): Flow<T> {
    val vm = this
    return flow {
        val response = request(Api) ?: throw IllegalArgumentException("数据非法，获取响应数据为空")
        emit(response)
    }.flowOn(Dispatchers.IO)
        .onCompletion { cause ->
            cause?.let {
                throw cause
            }
        }
}